import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../providers/private_chat_provider.dart';
import '../providers/user_provider.dart';

class ChatHelper {
  static Future<void> handleUserAvatarTap({
    required BuildContext context,
    required WidgetRef ref,
    required String targetUserId,
  }) async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null || currentUser.id == targetUserId) {
      return;
    }

    final privateChatNotifier = ref.read(privateChatProvider.notifier);

    var conversation = privateChatNotifier.getConversationBetweenUsers(
      currentUser.id,
      targetUserId,
    );

    String conversationId;

    if (conversation == null) {
      final userNotifier = ref.read(userProvider.notifier);
      final allUsers = userNotifier.getAllDefaultUsers();
      final targetUser =
          allUsers.where((u) => u.id == targetUserId).firstOrNull;

      if (targetUser == null) return;

      final newConversationId = await privateChatNotifier.createConversation(
        userId1: currentUser.id,
        userId2: targetUserId,
        userName1: currentUser.username,
        userName2: targetUser.username,
        userAvatar1: currentUser.avatar,
        userAvatar2: targetUser.avatar,
      );

      if (newConversationId == null) return;
      conversationId = newConversationId;
    } else {
      conversationId = conversation.conversationId;
    }

    if (context.mounted) {
      GoRouter.of(context).push(
        '/private-chat',
        extra: {'conversationId': conversationId, 'otherUserId': targetUserId},
      );
    }
  }

  static void handleChatListTap({
    required BuildContext context,
    required String conversationId,
    String? otherUserId,
  }) {
    GoRouter.of(context).push(
      '/private-chat',
      extra: {'conversationId': conversationId, 'otherUserId': otherUserId},
    );
  }
}
